package com.longcai.controller.exchangemall;


import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.zxing.WriterException;
import com.longcai.bean.ApiResult;
import com.longcai.bean.DateUtil;
import com.longcai.bean.PageHelper;
import com.longcai.entity.exchangemall.ClyjExchangeMall;
import com.longcai.entity.homegood.ClyjGoodsHomepage;
import com.longcai.entity.homegood.ClyjGoodsPics;
import com.longcai.entity.homegood.ClyjGoodsSpec;
import com.longcai.entity.homepage.ClyjSeckillGoods;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.exchangemall.ClyjExchangeMallService;
import com.longcai.service.goods.ClyjGoodsHomepageService;
import com.longcai.service.goods.ClyjGoodsSpecService;
import com.longcai.util.LoginUser;
import com.longcai.util.StringUtils;
import com.longcai.util.UUIDUtil;
import com.longcai.util.UserUtil;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;

/**
 * <p>
 * 兑换商城（积分商城，红包商城） 前端控制器
 * </p>
 * @author kh
 * @since 2019-04-15
 */
@Controller
@RequestMapping("/clyjExchangeMall")
public class ClyjExchangeMallController {

	
	private static Logger logger = LoggerFactory.getLogger(ClyjExchangeMallController.class);
	
	@Autowired
	private ClyjExchangeMallService clyjExchangeMallService;
	
	@Autowired
    private ClyjGoodsHomepageService clyjGoodsHomepageService;
	
	/****
	 * 根据条件查询兑换列表
	 * @param jsonobj
	 * @return
	 */
	@PostMapping(value = "getExchangeQueryList")
    @ResponseBody
	public PageTableResponse getExchangeList(ClyjExchangeMall clyjExchangeMall, PageHelper pageHelper){
		Page<ClyjExchangeMall> page =new Page<ClyjExchangeMall>(pageHelper.getStart(),pageHelper.getLength());
    	QueryWrapper<ClyjGoodsHomepage> w = new QueryWrapper<ClyjGoodsHomepage>();
    	if(clyjExchangeMall.getGoodsName()!=null && clyjExchangeMall.getGoodsName()!="")
    		w.like("goods_name", clyjExchangeMall.getGoodsName());
    	//获取当前用户信息
    	LoginUser loginUser = UserUtil.getLoginUser();
    	if(loginUser.getId()!=1)
    		w.eq("supplier_id", loginUser.getId());
    	w.orderByDesc("month_sales");
    	//查询出商品列表
    	try{
	    	List<ClyjGoodsHomepage> selectList = clyjGoodsHomepageService.selectList(w);
	    	//获取id集合
	    	QueryWrapper<ClyjExchangeMall> w2 = new QueryWrapper<ClyjExchangeMall>();
	    	List<String> list = new ArrayList<String>();
	    	Map<String,String> map = new HashMap<String,String>();
	    	for (ClyjGoodsHomepage clyjGoodsHomepage : selectList) {
	    		list.add(clyjGoodsHomepage.getGoodsId());
	    		map.put(clyjGoodsHomepage.getGoodsId(),clyjGoodsHomepage.getGoodsName()+","+clyjGoodsHomepage.getOriginalPrice());
			}
	    	w2.in("goods_id",list);
	        IPage<ClyjExchangeMall> sysRoleIPage = clyjExchangeMallService.selectPage(page, w2);
	        List<ClyjExchangeMall> records = sysRoleIPage.getRecords();
	        for (ClyjExchangeMall clyjExchangeMall1 : records) {
	        	clyjExchangeMall1.setOriginalPrice(map.get(clyjExchangeMall1.getGoodsId()).split(",")[1]);
	        	clyjExchangeMall1.setGoodsName(map.get(clyjExchangeMall1.getGoodsId()).split(",")[0]);
			}
	        sysRoleIPage.setRecords(records);
	        PageTableResponse pageTableResponse = new PageTableResponse(sysRoleIPage.getTotal(),
	                sysRoleIPage.getTotal(), sysRoleIPage.getRecords());
	        return pageTableResponse;
        }catch(Exception e){
        	e.printStackTrace();
        }
        return null;
	}
	
	/****
	 * 获取商品信息（商品名称，商品原价）
	 * @param clyjExchangeMall
	 * @return
	 */
	@GetMapping(value = "getExchange")
    @ResponseBody
	public ClyjGoodsHomepage getExchange(ClyjExchangeMall clyjExchangeMall){
		ClyjGoodsHomepage clyjGoodsHomepage=null;
		ClyjExchangeMall c=	clyjExchangeMallService.selectById(clyjExchangeMall.getId());
    	if(c!=null){
    		clyjGoodsHomepage=	clyjGoodsHomepageService.selectById(c.getGoodsId());
    	}
        return  clyjGoodsHomepage;
	}
	/**
     * 查询所有商品
     *
     * @return
     */
    @GetMapping(value = "getExchangeList")
    @ResponseBody
    public List<ClyjGoodsHomepage> getGoods(ClyjSeckillGoods sysRole) {
    	QueryWrapper<ClyjGoodsHomepage> w = new QueryWrapper<ClyjGoodsHomepage>();
    	//获取当前用户信息
    	LoginUser loginUser = UserUtil.getLoginUser();
    	if(loginUser.getId()!=1)
    		w.eq("supplier_id", loginUser.getId());
    	w.orderByDesc("month_sales");
    	QueryWrapper<ClyjExchangeMall> queryWrapper = new QueryWrapper<ClyjExchangeMall>();
    	queryWrapper.ne("id",sysRole.getId());
    	List<ClyjExchangeMall> selectList = clyjExchangeMallService.selectList(queryWrapper);
    	List<String> list = new ArrayList<String>();
        for (ClyjExchangeMall string : selectList) {
        	list.add(string.getGoodsId());
		}
        w.notIn("goods_id", list);
    	List<ClyjGoodsHomepage> sysRoleIPage = clyjGoodsHomepageService.selectList( w);
        return sysRoleIPage;
    }
	
	/**
     * 新增兑换
     */
    @PostMapping(value = "saveExchange")
    @ApiOperation(value = "新增兑换规则")
    @ResponseBody
    public ApiResult<?> save(@RequestBody ClyjExchangeMall clyjExchangeMall) throws IOException, WriterException {
    	if(clyjExchangeMall==null){
    		return ApiResult.fail("参数不合法");
    	}
    	if(StringUtils.isEmpty(clyjExchangeMall.getGoodsId())||StringUtils.isEmpty(clyjExchangeMall.getType())||StringUtils.isEmpty(clyjExchangeMall.getSort())
    			||StringUtils.isEmpty(clyjExchangeMall.getStock())||StringUtils.isEmpty(clyjExchangeMall.getSort())){
    		logger.error("兑换商城-新增兑换参数不合法:"+"getGoodsId:"+clyjExchangeMall.getGoodsId()+"-----"
    		+"Type:"+clyjExchangeMall.getType()+"-----"
    		);
    		return ApiResult.fail("参数不合法");
    	}
        	clyjExchangeMall.setId(UUIDUtil.uuid());
        	clyjExchangeMall.setCreater(UserUtil.getLoginUser().getUsername());
        	clyjExchangeMall.setCreateTime(DateUtil.dateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
        	Boolean b =clyjExchangeMallService.insert(clyjExchangeMall);
        	if(b){
        		ApiResult.success("新增成功");
        	}
        return ApiResult.fail("新增失败");
    }
    
    /**
     * 修改兑换规则
     *
     * @param clyjHeadlines
     * @return
     */
    @PutMapping(value = "/updateExchange")
    @ApiOperation(value = "修改兑换规则")
    @ResponseBody
    @PreAuthorize("hasAuthority('goods:exchange:update')")
    public  ApiResult<?> updateExchange(@RequestBody ClyjExchangeMall clyjExchangeMall) {
    	boolean b=clyjExchangeMallService.updateById(clyjExchangeMall);
    	if(b){
    		return	ApiResult.success("修改成功");
    	}
    	  return ApiResult.fail("修改失败------------");
    }  
    
    /**
     * 根据id获取兑换商城
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    @ApiOperation(value = "根据id获取兑换商城")
    @ResponseBody
    public ClyjExchangeMall get(@PathVariable String id) {
    	ClyjExchangeMall selectById = clyjExchangeMallService.selectById(id);
        return selectById;
    }
    
    @DeleteMapping("{id}")
    @ApiOperation(value = "删除")
    @ResponseBody
    @PreAuthorize("hasAuthority('goods:exchange:del')")
    public  ApiResult<?>  delete(@PathVariable String id) {
        Boolean b =clyjExchangeMallService.deleteById(id);
        if(b){
    		ApiResult.success("删除成功");
        }
        return ApiResult.fail("删除失败");
    }
}

